from bootstrap.microWebSrv import MicroWebSrv, _response, _client
from bootstrap.configs import configs


def handlerFunc_1(httpClient, httpResponse: _response, routeArgs=None):
    print("In HTTP handler 1")
    httpResponse.WriteResponseJSONOk({"aaa": "nnnnnn"})


def on_basic_config_submit(httpClient: _client, httpResponse, routeArgs=None):
    """
    处理最基本的配置项上传，将配置项写入config.json中
    """
    data = httpClient.ReadRequestPostedFormData()
    configs.update(data)
    with open("bootstrap/assets/successful.html", 'r') as f:
        data = f.read()
        httpResponse.WriteResponseOk(contentType="text/html", content=data)

def web_page(httpClient: _client, httpResponse: _response):
    """生成网页内容"""

    with open("bootstrap/assets/control.html", 'r') as f:
        data = f.read()
        data = data.replace("ETT_STA_SSID", configs.config["ssid"]).replace(
            "ETT_NAME",  configs.config["name"]).replace(
            "ETT_AS_GND_CTRL", "selected" if (configs.config["role"] == "ground-control") else "").replace(
                "ETT_AS_LOCO_CTRL",  "selected" if (configs.config["role"] == "locomotive-control") else "")
        httpResponse.WriteResponseOk(contentType="text/html", content=data)


ROUTES_WEBPAGE = [
    ("/", "GET", web_page),
    ("relative_url_route_1", "GET", handlerFunc_1),
    ("/config-submit", "POST", on_basic_config_submit),]
